<template>
	<view class="centers">
		<u-sticky bgColor="#fff">
			<u-tabs :activeStyle="{
				color: '#606266',
				fontWeight: 'bold',
				transform: 'scale(1.05)'
			}" lineColor="#fff" :scrollable="false" :list="btnList" :current="currentIndex"
				@click="checkCurrentType()"></u-tabs>
			<view>
				<u-notice-bar text="消息可能有延迟，多刷新，常切换！！！"></u-notice-bar>
			</view>
		</u-sticky>
		<view class="list-w" v-show="currentIndex == 0">
			<view class="list" v-for="(item, index) in messageList" :key="index">
				<view class="date">
					<view style="background-color: #eee;; height: 2rpx; flex: 28%;"></view>
					<view style="margin: 20rpx; color: rgba(16, 16, 16, 1);font-size: 28rpx">
						{{ item.createTime }}
					</view>
					<view style="background-color: #eee;; height: 2rpx; flex: 28%;"></view>
				</view>
				<view class="mess-list" v-for="(it, inx) in item.list" :key="inx">
					<image mode="widthFix" class="head" :src="it.imgUrl"></image>
					<view style="width: 80%;">
						<view style="font-size: 24rpx;" :class="it.role == 1 ? 'cv' : ''">
							{{ it.openid == paramsMess.openid ? "自己" : "对方" }} <text
								style="color: #555; margin-left: 40rpx;">{{it.createTimex}}</text>
						</view>
						<view style="margin-top: 10rpx;">
							<view :class="it.openid == paramsMess.openid ? 'actives' : ''"
								style="margin-left: 60rpx; margin-bottom: 20rpx; color: #13ce66;word-wrap: break-word;word-break:break-all;">
								{{ it.context }}
							</view>
							<view>
								<view v-for="(el, xe) in it.newTypeData" :key="xe">
									<view style="font-weight: 500;color: #222; font-size: 32rpx; margin-top: 20rpx;margin-bottom: 5rpx;text-align: center;">
										{{ el.typeName }}
									</view>
									<!-- <view style="margin: 20rpx 0 20rpx 40rpx">
										{{ el.typeText }}
									</view> -->
									<!-- <view class="img" v-for="(imgItem,imgIndex) in el.imgs" :key="imgIndex">
										<uni-file-picker readonly v-model="imgItem.url" :imageStyles="imageStyles"
											fileMediatype="image" file-extname="png,jpg" />
									</view> -->
									<image class="imgs-l" style="margin:10rpx" mode="widthFix"
										:show-menu-by-longpress='true' v-for="(img, z) in el.imgs" :key="z"
										:src="img.url" @click="prviewImg(img.url)">
									</image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-if="currentList.length == count">
				<u-divider text="没有更多了..."></u-divider>
			</view>
		</view>
		<!-- 发送消息 -->
		<view id="mess" ref="myDom" v-show="currentIndex == 1" class="seed">
			<u-textarea height="200rpx" placeholder="请输入内容" v-model="paramsMess.context" maxlength="999"
				show-word-limit>
			</u-textarea>
			<view class="custom-style">
				<u-button @click="addType" size="small" type="primary">添加分类</u-button>
			</view>
			<view v-for="(item, index) in paramsMess.typeData" :key="index">
				<view class="add-type">
					<view class="add-mess">
						<view class="add-name">图片分类ID：</view>
						<view>{{ index + 1 }}</view>
					</view>
					<view class="add-mess">
						<view class="add-name">图片分类名：</view>
						<view>
							<u-textarea type="text" height="60rpx" placeholder="请输入图片分类名" v-model="item.typeName"
								maxlength="30">
							</u-textarea>
						</view>
					</view>
					<!-- <view class="add-mess">
						<view class="add-name">图片评论：</view>
						<view>
							<u-textarea height="60rpx" placeholder="请输入图片评论" v-model="item.typeText" maxlength="30"
								show-word-limit>
							</u-textarea>
						</view>
					</view> -->
					<view class="add-mess">
						<view class="add-name">图片添加：</view>
						<view>
							<uni-file-picker ref="pickerRef" v-model="item.imgs" fileMediatype="image"
								file-extname="png,jpg" mode="grid" @select="select($event,index)"
								@delete="deleteImg($event,index)" :autoUpload="false" limit="9" title="最多选择9张图片">
							</uni-file-picker>
						</view>
					</view>
					<view class="" style="display: flex;justify-content: flex-end;margin-right: 20rpx;">
						<view class="btn-del custom-style">
							<u-button size="small" type="error" @click="deleteType(index)">删除分类</u-button>
						</view>
					</view>
				</view>
			</view>
			<view style="display: flex;justify-content: flex-end;margin-right: 20rpx;">
				<view class="custom-style" :class="paramsMess.typeData[0] ? '' : 'istop'">
					<u-button app-parameter="" size="small" type="success" @click="sendMessage">立即发送</u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		friendlyFormatTime,
		judgeTime
	} from '../../../utils/util.js'

	import {
		mapMutations
	} from 'vuex'

	import {
		GetOpenid,
		InsertMsg_X
	} from "../../../api/user.js"

	export default {
		data() {
			return {
				orderNo: '',
				count: 0,
				currentList: [],
				paramsMess: {
					openid: "",
					orderNo: "",
					context: "", //发送消息的内容
					typeData: [{
							typeName: "接受货物信息", //图片分类名
							img: [], // 上传的图片
							imgs: [], // 回显得图片
						},
						{
							typeName: "样品标签检查", //图片分类名
							img: [], // 上传的图片
							imgs: [],
						},
						{
							typeName: "样品编带检查", //图片分类名
							img: [], // 上传的图片
							imgs: [],
						},
						{
							typeName: "样品封装检测", //图片分类名
							img: [], // 上传的图片
							imgs: [],
						},
						{
							typeName: "样品引脚检测", //图片分类名
							img: [], // 上传的图片
							imgs: [],
						},
						{
							typeName: "样品丙酮擦拭", //图片分类名
							img: [], // 上传的图片
							imgs: [],
						},
						{
							typeName: "样品刮擦测试", //图片分类名
							img: [], // 上传的图片
							imgs: [],
						},
						{
							typeName: "样品封装尺寸测量", //图片分类名
							img: [], // 上传的图片
							imgs: [],
						}
					]
				},
				listData: {
					orderNo: '',
					pageIndex: 1,
					size: 10
				},
				btnList: [{
						name: "消息列表"
					},
					// {
					// 	name: '发送消息'
					// },
				],
				currentIndex: 0,
				//消息列表
				messageList: [],
				imageValue: [],
				//预览图片列表
				imgPrevList: [],
				//定时器
				timer: '',
				imageStyles: {
					width: 90,
					height: 90,
				},
			};

		},
		methods: {
			...mapMutations('user', ['setToken']),

			// 点击查看详情的消息切换按钮
			checkCurrentType(e) {
				// console.log(e)
				this.currentIndex = e.index;
				if (e.index == 0) {
					this.listData.pageIndex = 1
					this.currentList = []
					this.messageList = []

					this.getMessageList(this.listData)
				}
			},

			//添加分类
			addType() {
				console.log("添加分类");
				this.paramsMess.typeData.push({
					typeName: "", //图片分类名
					// typeText: "", // 图片分类
					img: [], // 上传的图片
					imgs: [],
				});
				console.log("添加分类", this.paramsMess.typeData);
			},

			// 删除分类
			deleteType(index) {
				this.paramsMess.typeData.splice(index, 1);
			},

			// 获取上传状态
			select(e, index) {
				console.log('选择文件：', e, index)

				e.tempFiles.forEach((item, i) => {
					console.log(index);
					let data = {
						name: item.name,
						extname: item.extname,
						url: item.url,
					}
					if (item.size / 1024 / 1024 < 1.5) {
						this.uploadFiles(item.url, index, data)
					} else {
						this.comImg(item.url, index, data)
					}
				})
			},

			// 图片压缩
			comImg(src, index, data) {
				uni.compressImage({
					src: src,
					quality: 40,
					success: res => {
						this.uploadFiles(res.tempFilePath, index, data)
						// this.uploadObs(x.url, index, data)
					}
				})
			},

			// 删除图片
			deleteImg(e, index) {
				let num = this.paramsMess.typeData[index].imgs.findIndex(v => v.url === e.tempFilePath);
				this.paramsMess.typeData[index].img.splice(num, 1);
				console.log(this.paramsMess.typeData[index]);
			},

			// 手动调用上传代码
			uploadFiles(tempFilePath, index, data) {
				const _that = this
				return new Promise((resolve) => {
					uni.uploadFile({
						url: 'https://wechat.atptest.com:44387/api/PCApplet/UploadLargeFileOBS',
						filePath: tempFilePath,
						name: 'file',
						// formData: {
						// 	user: 'test'  目前formData自动生成了 file:tempFilePath，如果还向添加其他参数才写
						// },
						success(res) {
							console.log('res', res);
							resolve()
							let json_data = JSON.parse(res.data)
							// 上传失败
							if (json_data['errCode'] == 0) {
								return uni.showToast({
									title: json_data['error_message'],
									icon: 'none',
									duration: 2000
								});
							}
							// 上传成功代码
							_that.paramsMess.typeData[index].img.push(json_data.data)
							_that.paramsMess.typeData[index].imgs.push(data)
						},

					})
				})
			},

			getOpenId() {
				GetOpenid().then((res) => {
					this.paramsMess.openid = res
				})
			},

			// 消息列表
			getMessageList(data) {
				uni.showLoading({
					title: '加载中',
				});
				let _that = this
				uni.request({
					url: 'https://wechat.atptest.com:44387/api/PCApplet/ListMsg_Admin',
					method: 'GET',
					data: data,
					success(res) {
						const {
							data
						} = res.data
						if (data) {
							// let a = data.items.map((item) => {
							// 	item.typeData.forEach((i) => {
							// 		i.img = i.img.map((j) => {
							// 			return {
							// 				"name": j,
							// 				"extname": j,
							// 				"url": j,
							// 			}
							// 		})
							// 	})
							// 	return item
							// })

							_that.count = data.totalCount
							_that.currentList = _that.currentList.concat(data.items)
							// _that.messageList = _that.dataResort(_that.currentList)
							_that.messageList = _that.dataResort(data.items)
							_that.messageList.forEach(el => {
								el.createTime = judgeTime(el.createTimes);
								el.list.forEach(it => {
									it.createTimex = friendlyFormatTime(it.createTime);
								});
							});
							console.log("_that.messageList", _that.messageList);
							let list = [];
							for (let i = 0; i < _that.messageList.length; i++) {
								for (let j = 0; j < _that.messageList[i].list.length; j++) {
									for (
										let k = 0; k < _that.messageList[i].list[j].newTypeData.length; k++
									) {
										for (
											let m = 0; m < _that.messageList[i].list[j].newTypeData[k].imgs
											.length; m++
										) {
											list.push(_that.messageList[i].list[j].newTypeData[k].imgs[m].url);
										}
									}
								}
							}
							//预览图片列表
							_that.imgPrevList = list;
						}
						_that.timer = setTimeout(() => {
							uni.hideLoading();
						}, 200)
					}
				})
			},

			//图片预览
			prviewImg(img) {
				let urls = []
				let currentImg = 0
				for (var i = 0; i < this.imgPrevList.length; i++) {
					if (img == this.imgPrevList[i]) {
						currentImg = i
					}
					urls.push(this.imgPrevList[i])
				}
				uni.previewImage({
					urls: urls,
					current: currentImg
				});
			},


			dataResort(data) {
				// 定义空数组，用于存储新组装的数据
				console.log("data", data);
				let newArr = [];
				// 遍历数组
				data.forEach((item, i) => {
					// 默认当前操作的数据下标 -1
					let index = -1;
					// 判断数组中是否已经存在当前遍历数据的时间
					let isExists = newArr.some((newItem, j) => {
						if (
							item.createTime.substring(0, 10) ==
							newItem.createTime.substring(0, 10)
						) {
							// 存在就保存当前数据下标  用于插入数据
							index = j;
							return true;
						}
					});
					// 如果没有就存储一条新对象数据
					if (!isExists) {
						newArr.push({
							createTime: item.createTime.substring(0, 10),
							createTimes: item.createTime,
							list: [item]
						});
					} else {
						// 如果有就插入到已存在的对象中
						newArr[index].list.push(item);
					}
				});
				console.log("返回新数组", newArr);
				// 返回新数组
				return newArr;
			},


			//立即发送消息
			sendMessage() {
				if (this.paramsMess.context == "" && this.paramsMess.typeData.length == 0)
					return uni.showToast({
						icon: 'error',
						title: '消息不能为空！！！'
					})
				if (this.paramsMess.typeData.length > 0) {
					let X = this.paramsMess.typeData.find(v => {
						return v.typeName == "";
					});
					let Z = this.paramsMess.typeData.find(v => {
						return v.img.length == 0;
					});
					if (X) {

						return uni.showToast({
							icon: 'error',
							title: '分类名不能为空！！！'
						})
					} else if (Z) {

						return uni.showToast({
							icon: 'error',
							title: '图片不能为空！！！'
						})
					}
				}

				InsertMsg_X(this.paramsMess).then((res) => {
					this.listData.pageIndex = 1
					this.currentList = []
					this.messageList = []
					this.currentIndex = 0
					this.getMessageList(this.listData)
					this.paramsMess.context = ''
					this.paramsMess.typeData = []
					uni.showToast({
						title: '发送成功！',
						icon: 'success'
					})
				})


			}
		},

		onLoad(option) {
			// console.log(option.i);
			this.orderNo = option.i
			this.paramsMess.orderNo = option.i
			this.listData.orderNo = option.i
			this.getOpenId()
			this.getMessageList(this.listData)
		},
		onReachBottom() {
			if (this.currentIndex == 1) {
				return
			}
			this.listData.pageIndex++
			this.getMessageList(this.listData)
		}
	}
</script>

<style lang="scss" scoped>
	.name {
		color: rgba(16, 16, 16, 1);
		font-size: 32rpx;
		text-align: left;
		font-family: SourceHanSansSC-medium;
		flex: 1;
		border-right: 4rpx solid #ccc;
		font-weight: 700;
	}

	.mess {
		flex: 1;
		margin-left: 48rpx;
		color: rgba(140, 140, 140, 1);
		font-size: 32rpx;
		font-weight: 700;
	}

	.cv {
		color: #666;
	}


	.istop {
		margin-top: -80rpx !important;
	}

	.num {
		height: 104rpx;
		color: rgba(16, 16, 16, 1);
		font-size: 72rpx;
	}

	.img-x {
		display: flex;
		flex-wrap: wrap;
	}

	.img-s {
		width: 46%;
		margin: 10rpx;
		height: 600rpx;
	}

	.heads {
		display: flex;
		justify-content: center;
		border-bottom: 4rpx solid #ccc;
	}


	.date {
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
	}


	.btns {
		flex: 1;
		text-align: center;
		padding-bottom: 16rpx;

	}

	.btns view {
		flex: 1;
		color: rgba(16, 16, 16, 1);
		font-size: 28rpx;
		height: 80rpx;
		line-height: 80rpx;
	}

	.btns view:first-child {
		border-right: 4rpx solid #ccc;
	}

	.active {
		color: rgba(65, 50, 192, 1) !important;
		font-weight: 700 !important;
	}

	.actives {
		color: rgb(194, 51, 40) !important;
		font-weight: 700 !important;
	}


	.mess-list {
		display: flex;
		/* align-items: center; */
		margin-top: 32rpx;
		margin-left: 20rpx;
	}

	.list-w {
		padding: 0 20rpx;
	}

	.seed {
		padding: 20rpx;
		// overflow-y: scroll;
		// height: 82%;
	}

	.custom-style {
		margin: 20rpx 0;
		width: 160rpx !important;
	}

	.add-type {
		/* height: 400px; */
		// border: 2rpx solid #ccc;
		margin-bottom: 40rpx;
		box-shadow: 10rpx 10rpx 20rpx rgba(0, 0, 0, 0.5);
	}

	.add-mess {
		display: flex;
		align-items: center;
		margin: 20rpx;
	}

	.add-name {
		min-width: 180rpx !important;

		text-align: right;
		font-size: 26rpx
	}

	.add-mess view:last-child {
		width: 100%;
	}

	.imgs-l {
		width: 160rpx !important;
		height: 160rpx !important;
	}

	.head {
		width: 80rpx !important;
		height: 80rpx !important;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.imagePopup {
		width: 100%;
		height: 1000rpx;
		margin: 0;
	}

	/deep/ .uni-file-picker__container {
		display: flex;
		flex-wrap: wrap;
		justify-content: left;
	}
</style>